package com.example.xmpic.ui.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.example.xmpic.support.FunPath;
import com.example.xmpic.ui.data.CameraLocalFile;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author skygge
 * @date 2020/6/24.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：本地文件读取
 */
public class LocalFileManager {

    private static final String TAG = LocalFileManager.class.getSimpleName();
    private volatile static LocalFileManager mInstance = null;
    private SimpleDateFormat mYearFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static LocalFileManager getInstance(){
        if (mInstance == null){
            synchronized (LocalFileManager.class){
                if (mInstance == null) {
                    mInstance = new LocalFileManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取当前时间的时间戳
     * @param time 选择的时间
     * @return
     */
    public String getTimeStamp(String time){
        String timeStamp = null;
        SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date;
        try{
            date = mFormat.parse(time);
            long l = date.getTime();
            timeStamp = String.valueOf(l);
        } catch(ParseException e){
            e.printStackTrace();
        }
        return timeStamp;
    }

    public String getBeginDate(String datetime){
        return mYearFormat.format(new Date(Long.parseLong(datetime)));
    }

    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描
     */
    public List<CameraLocalFile> getLocalImages(Context context, String devSn){
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        List<CameraLocalFile> mImageFile = new ArrayList<>();
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver mContentResolver = context.getContentResolver();
        // 只查询jpeg和png的图片
        Cursor  mCursor = mContentResolver.query(mImageUri, null,
                "("+MediaStore.Images.Media.MIME_TYPE + "=? or "
                        + MediaStore.Images.Media.MIME_TYPE + "=?"+ ") and "
                        + MediaStore.Images.Media.DATA +" like ?",
                new String[] { "image/jpeg", "image/png" ,"%" + FunPath.PATH_CAPTURE_TEMP + File.separator + devSn + "%"},
                MediaStore.Images.Media.DATE_MODIFIED  + " DESC");
        if (mCursor!=null) {
            while (mCursor.moveToNext()) {
                String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));// 获取图片的路径
                String modify = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED));
                String time = mYearFormat.format(new Date(Long.parseLong(modify)*1000));
                File file = new File(path);
                CameraLocalFile cameraLocalFile = new CameraLocalFile();
                cameraLocalFile.setSerial(devSn);
                cameraLocalFile.setFilename(file.getName());
                cameraLocalFile.setFilepath(path);
                cameraLocalFile.setModifyTime(time);
                cameraLocalFile.setIsLocalFile(true);
                mImageFile.add(cameraLocalFile);
                // 拿到第一张图片的路径
            }
            mCursor.close();
        }
        return mImageFile;
    }

    /**
     * 利用ContentProvider扫描手机中的的录像
     */
    public List<CameraLocalFile> getLocalVideos(Context context, String devSn) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        List<CameraLocalFile> mVideoFile = new ArrayList<>();
        Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        ContentResolver mContentResolver = context.getContentResolver();
        Cursor mCursor = mContentResolver.query(mImageUri, null,
                MediaStore.Video.Media.DATA +" like ?",
                new String[] {  "%" + FunPath.PATH_VIDEO + File.separator + devSn + "%"},
                MediaStore.Video.Media.DATE_MODIFIED  + " DESC");
        if (mCursor != null) {
            while (mCursor.moveToNext()) {
                String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.DATA));// 获取录像的绝对路径
                String size = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.SIZE));// 获取录像文件大小
                File file = new File(path);
                String fileName, downTime;
                if (file.getName().contains("_")){
                    String[] files = file.getName().split("_");
                    fileName = files[1];
                    downTime = files[0] + " " + fileName.substring(0, fileName.indexOf("-"));
                }else {
                    downTime = null;
                    fileName = file.getName();
                }
                if (downTime!=null) {
                    CameraLocalFile videoFile = new CameraLocalFile();
                    videoFile.setSerial(devSn);
                    videoFile.setFilename(fileName);
                    videoFile.setFilepath(path);
                    videoFile.setFileSize(size);
                    videoFile.setDownTime(getTimeStamp(downTime));
                    videoFile.setIsLocalFile(true);
                    mVideoFile.add(videoFile);
                }
            }
            mCursor.close();
        }
        return mVideoFile;
    }

    /**
     * 通知android媒体库更新文件夹
     * @param filePath ilePath 文件绝对路径
     */
    public void scanFile(Context context, String filePath) {
        try {
            MediaScannerConnection.scanFile(context, new String[]{filePath}, null, (path, uri) -> {});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
